﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Project.DTO;
using Project.IService;
using Project.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Project.WebAPI.Controllers
{
    /// <summary>
    /// 设计工具
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class DesignToolController : ControllerBase
    {
        private readonly IDesignToolService designService;
        private readonly IMapper mapper;

        public DesignToolController(IDesignToolService designService, IMapper mapper)
        {
            this.designService = designService;
            this.mapper = mapper;
        }

        /// <summary>
        /// 所有设计工具
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var list = await designService.GetList().OrderBy(n => n.Order).Select(n => new { n.Id, n.Title,n.Order}).ToListAsync();
            return Ok(list);
        }

        /// <summary>
        /// 根据Id获取设计工具对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(Guid id)
        {
            var tool = await designService.GetList(n => n.Id == id).Select(n => new { n.Id, n.Title, n.Order }).FirstOrDefaultAsync();
            return Ok(tool);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="tool">工具对象</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Post(DesignToolPost tool)
        {
            var dt = mapper.Map<DesignTool>(tool);
            await designService.AddAsync(dt);
            //return CreatedAtAction(nameof(Get), new { id = dt.Id });
            return Ok(new { id = dt.Id });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public IActionResult Delete(Guid id)
        {
            designService.MarkRemove(id);
            return Ok("删除完成");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> Edit(Guid id, DesignToolPut dto)
        {
            var tool = await designService.GetEntityAsync(n => n.Id == id);
            if (tool.Id != dto.Id)
                return BadRequest("尝试修改他人数据，请求被拒绝！");
            await designService.EditAsync(mapper.Map<DesignTool>(dto));
            return Ok("修改完成！");

        }
    }
}
